/**
 * <p>Title: LoginSuccessHandler.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: SiySoft</p>
 * @author liguanghui
 * @date 2015年5月25日
 * @version 1.0
 */
package com.siysoft.tc.base.service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import com.siysoft.tc.base.bean.to.Manager;
import com.siysoft.tc.base.bean.to.ManagerLog;
import com.tc.base.dao.BaseDAO;

public class AdminLoginSuccessHandler extends
		SimpleUrlAuthenticationSuccessHandler {

	private String LOCAL_SERVER_URL = "/admin/index.htm";
	private String defaultTargetUrl;
	private boolean forwardToDestination = false;
	protected Log logger = LogFactory.getLog(getClass());
	@Autowired
	private BaseDAO baseDAO;
	
	private RequestCache requestCache = new HttpSessionRequestCache();

	public void afterPropertiesSet() throws Exception {
	}

	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		System.out.println("onAuthenticationSuccess");
		Manager user = (Manager) authentication.getPrincipal();
		Set<String> set = new HashSet();
		Collection<GrantedAuthority> authories = (Collection<GrantedAuthority>) authentication
				.getAuthorities();
		boolean yesOrNo = false;
		for (GrantedAuthority grantedAuthority : authories) {
			String str = grantedAuthority.getAuthority();
			if(Objects.equals("ROLE_SEM", str)){
				yesOrNo = true;
			}
			set.add(str);
		}
		request.getSession().setAttribute("manager", user);
		request.getSession().setAttribute("authorities", set);
		ManagerLog sysUserLog = new ManagerLog();
		sysUserLog.setManagerId(String.valueOf(user.getManagerId()));
		sysUserLog.setLoginTime(new Timestamp(Calendar.getInstance()
				.getTimeInMillis()));
		sysUserLog.setIpAddr(getIpAddress(request));
		sysUserLog.setUserName(user.getUsername());
		sysUserLog.setAccount(user.getUsername());
		System.out.println("管理员：" + sysUserLog.getUserName() + "登陆了");
		this.baseDAO.save(sysUserLog);
		SavedRequest savedRequest = requestCache.getRequest(request,
				response);
//		if (savedRequest == null) {
			System.out.println("savedRequest is null ");
			// 用户判断是否要使用上次通过session里缓存的回调URL地址
			int flag = 0;
			// 通过提交登录请求传递需要回调的URL callCustomRediretUrl
			if (request.getSession().getAttribute("callCustomRediretUrl") != null
					&& !"".equals(request.getSession().getAttribute(
							"callCustomRediretUrl"))) {
				String url = String.valueOf(request.getSession()
						.getAttribute("callCustomRediretUrl"));
				// 若session 存在则需要使用自定义回调的URL 而不是缓存的URL
				super.setDefaultTargetUrl(url);
				super.setAlwaysUseDefaultTargetUrl(true);
				flag = 1;
				request.getSession().setAttribute(
						"callCustomRediretUrl", "");
			}
			// 重设置默认URL为主页地址
			if (flag == 0) {
				super.setDefaultTargetUrl(this.defaultTargetUrl);
			}
			if(yesOrNo){
				super.setDefaultTargetUrl("/sem/indexForSEM.htm");
			}
			super.onAuthenticationSuccess(request, response,
					authentication);
			clearAuthenticationAttributes(request);
			return;
//		}
//		// targetUrlParameter 是否存在
//		String targetUrlParameter = getTargetUrlParameter();
//		if (isAlwaysUseDefaultTargetUrl()
//				|| (targetUrlParameter != null && StringUtils
//						.hasText(request
//								.getParameter(targetUrlParameter)))) {
//			requestCache.removeRequest(request, response);
//			super.setAlwaysUseDefaultTargetUrl(false);
//			super.setDefaultTargetUrl("/");
//			super.onAuthenticationSuccess(request, response,
//					authentication);
//			return;
//		}
		// 清除属性
		

//		// Use the DefaultSavedRequest URL
//		String targetUrl = savedRequest.getRedirectUrl();
//		logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
//		if (targetUrl != null && "".equals(targetUrl)) {
//			targetUrl = LOCAL_SERVER_URL;
//		}
//		getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

	public void setDefaultTargetUrl(String defaultTargetUrl) {
		this.defaultTargetUrl = defaultTargetUrl;
	}

	public boolean isForwardToDestination() {
		return this.forwardToDestination;
	}

	public void setForwardToDestination(boolean forwardToDestination) {
		this.forwardToDestination = forwardToDestination;
	}

	public String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
